package com.cph.tool.gen.controller;

import com.cph.common.http.HttpResponseResult;
import com.cph.common.http.HttpStatus;
import com.cph.common.util.SqlUtil;
import com.cph.common.util.StringUtils;
import com.cph.common.util.text.Convert;

import com.cph.framework.page.PageDomain;
import com.cph.framework.page.TableDataInfo;
import com.cph.framework.page.TableSupport;
import com.cph.tool.gen.domain.GenTable;
import com.cph.tool.gen.domain.GenTableColumn;
import com.cph.tool.gen.service.IGenTableColumnService;
import com.cph.tool.gen.service.IGenTableService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author changph
 */
@RestController
@RequestMapping("/tool/gen")
@Slf4j
public class GenController {

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @GetMapping("/list")
    public TableDataInfo genList(GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{talbleId}")
    public HttpResponseResult getInfo(@PathVariable Long talbleId) {
        GenTable table = genTableService.selectGenTableById(talbleId);
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        return HttpResponseResult.success(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    public TableDataInfo dataList(GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{talbleId}")
    public TableDataInfo columnList(Long tableId) {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */
//    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public HttpResponseResult importTableSave(String tables) {
        try {
            String[] tableNames = Convert.toStrArray(tables);
            // 查询表信息
            List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
            genTableService.importGenTable(tableList);
            return HttpResponseResult.success();

        } catch (Exception e) {
            return HttpResponseResult.error(500,"importTableSave has Exception");
        }
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping
    @Transactional
//    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    public HttpResponseResult editSave(@Validated @RequestBody GenTable genTable) {
        try {
            System.out.println(genTable.getParams().size());
            genTableService.validateEdit(genTable);
            genTableService.updateGenTable(genTable);
            return HttpResponseResult.success();
        } catch (Exception e) {
            return HttpResponseResult.error(500,"editSave has Exception");
        }
    }

//    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public HttpResponseResult remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return HttpResponseResult.success();
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableId}")
    public HttpResponseResult preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return HttpResponseResult.success(dataMap);
    }

    /**
     * 生成代码
     */
//    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        try {
            byte[] data = genTableService.generatorCode(tableName);
            genCode(response, data);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("genCode has exception={}",e.toString());
        }
    }

    /**
     * 批量生成代码
     */
//    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        try {
            String[] tableNames = Convert.toStrArray(tables);
            byte[] data = genTableService.generatorCode(tableNames);
            genCode(response, data);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("batchGenCode has exception={}",e.toString());
        }
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}